package com.bc.bcapi.service;

import com.bc.bcapi.dao.T_ProjectMapper;
import com.bc.bccore.redis.RedisService;
import com.bc.bccore.webconfig.WebConfig;
import com.bc.bcmodel.consts.GlobalSettings;
import com.bc.bcmodel.consts.RedissCacheKey;
import com.bc.bcmodel.domain.T_ProjectModel;
import com.bc.bcmodel.enums.EmailTemplateEnum;
import com.bc.bcmodel.req.*;
import com.bc.bcmodel.resp.MngSendEmailResp;
import com.bc.bcmodel.resp.UserCookieResp;
import com.bc.commoncore.security.AES;
import com.bc.commoncore.security.DES;
import com.bc.commoncore.util.*;
import com.bc.commonentity.common.JsonResult;
import com.bc.commonentity.enums.HttpReturnRnums;
import com.bc.commonentity.enums.SeqNameEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.math.BigInteger;

import com.bc.bcapi.dao.T_User_seller_infoMapper;
import com.bc.bcmodel.domain.T_User_seller_infoModel;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Name T_User_seller_infoService * @Description * @Author generation * @Date 2018/8/12 20:44:14 * @Version 1.0
 **/
@Service
public class T_User_seller_infoService {
    private static final Logger LOGGER = LoggerFactory.getLogger(T_User_seller_infoService.class);
    private static final String DOMAIN = "http://bcseller.xiats.com/";
    @Resource
    T_User_seller_infoMapper t_User_seller_infoMapper;

    @Resource
    T_ProjectMapper t_ProjectMapper;

    @Resource
    T_SequenceService t_SequenceService;
    @Resource
    CommonImgCodeService commonImgCodeService;
    @Resource
    T_Mng_email_sysService t_mng_email_sysService;
    @Resource
    T_User_walletService t_user_walletService;
    @Resource
    RedisService redisService;

    /**
     * 验证邮箱是否使用过(是否已经注册过)
     *
     * @param req
     * @return
     */
    public JsonResult checkEmailUsed(UserEmailCheckReq req) {
        HttpReturnRnums paramsCheckEnum = req.paramsCheck();
        if (paramsCheckEnum != HttpReturnRnums.Success) {
            return new JsonResult(paramsCheckEnum);
        }
        T_User_seller_infoModel queryModel = new T_User_seller_infoModel();
        queryModel.setEmail(req.getEmail());
        queryModel.setStatus("1");
        T_User_seller_infoModel queryResultModel = findByNamedParam(queryModel);
        if (queryResultModel != null) {
//            return new JsonResult(HttpReturnRnums.EMAIL_IS_EXIST);
            return new JsonResult(HttpReturnRnums.Success);
        }
        return new JsonResult(HttpReturnRnums.USER_NOT_EXIST);
    }

    /**
     * 注册
     * status{0:注册未激活;1:注册已激活;}
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = {
            Exception.class}, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public JsonResult signUp(UserSignUpReq req, HttpServletRequest request) throws Exception {
        HttpReturnRnums paramsCheckEnum = req.paramsCheck();
        if (paramsCheckEnum != HttpReturnRnums.Success) {
            return new JsonResult(paramsCheckEnum);
        }
        String cookie_name = GlobalSettings.SELLERIMGCode_COOKIE_NAME;
        if (!commonImgCodeService.checkCode(request, req.getVcode(), cookie_name)) {
            return new JsonResult(HttpReturnRnums.VCODE_IS_EMPTY);
        }
        T_User_seller_infoModel queryModel = new T_User_seller_infoModel();
        queryModel.setEmail(req.getEmail());
        T_User_seller_infoModel queryResultModel = findByNamedParam(queryModel);
        if (queryResultModel != null) {
            if (StringUtils.equals("0", queryResultModel.getStatus())) {
                sendActivateEmail(queryResultModel, request);
                return new JsonResult(HttpReturnRnums.Success);
            }
            return new JsonResult(HttpReturnRnums.EMAIL_IS_EXIST);
        }
        String userId = t_SequenceService.genSequence(SeqNameEnum.USER_INFO_SEQ);
        if (!StringUtils.isEmpty(req.getInviteCode())) {
            try {
                String invite_Userid = DES.decrypt(req.getInviteCode());
                req.setInviteCode(invite_Userid);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        T_User_seller_infoModel insertModel = req.convertor(userId);
        int ret = insert(insertModel);
        if (ret <= 0) {
            return new JsonResult(HttpReturnRnums.SystemError);
        }
        //创建用户钱包
        t_user_walletService.createWallet(userId);
        sendActivateEmail(insertModel, request);
        return new JsonResult(HttpReturnRnums.Success);
    }

    /**
     * TODO send activate email
     *
     * @param userInfo
     */
    private void sendActivateEmail(T_User_seller_infoModel userInfo,
                                   HttpServletRequest request) {
//        String activateCode = AES.aesEncrypt(userInfo.getUser_id() + "_MARVEL_" + userInfo.getEmail());
//        String url = DOMAIN + "nologon/marvel/activate?code=" + activateCode;
//        setEmail(userInfo.getEmail(), url, EmailTemplateEnum.REGISTER, request);
        UserPasswordRegisterReq userPasswordRegisterReq = new UserPasswordRegisterReq();
        userPasswordRegisterReq.setUser_id(userInfo.getUser_id());
        userPasswordRegisterReq.setEmail(userInfo.getEmail());
        userPasswordRegisterReq.setCreate_time(DateUtil.getToday());
        String code = JsonUtil.obj2string(userPasswordRegisterReq);
        code = AES.aesEncrypt(code);
        try {
            code = URLEncoder.encode(code, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String email = userInfo.getEmail();
        /**设置激活地址开始*/
        String url = WebConfig.getSitePath() + "/userpassport/activate?code=" + code;
        /**设置激活地址结束*/
        //发送修改密码邮件
        List<MngSendEmailResp> list = new ArrayList<MngSendEmailResp>();
        MngSendEmailResp zhanghao = new MngSendEmailResp();
        zhanghao.setKey("email");
        zhanghao.setValue(email);
        list.add(zhanghao);
        MngSendEmailResp callbackUrl = new MngSendEmailResp();
        callbackUrl.setKey("callbackurl");
        callbackUrl.setValue(url);
        list.add(callbackUrl);

        t_mng_email_sysService.sendSystemEmailSync(
                EmailTemplateEnum.REGISTER, email, JsonUtil.obj2string(list), request);
    }

    /**
     * 登录
     *
     * @param req
     * @param request
     * @param response
     * @return
     */
    public JsonResult logon(UserLogonReq req, HttpServletRequest request,
                            HttpServletResponse response) {
        HttpReturnRnums paramsCheckEnum = req.paramsCheck();
        if (paramsCheckEnum != HttpReturnRnums.Success) {
            return new JsonResult(paramsCheckEnum);
        }
        //暂时不用
//        String cookie_name = GlobalSettings.SELLERIMGCode_COOKIE_NAME;
//        if(!commonImgCodeService.checkCode(request, req.getVcode(), cookie_name)){
//            return new JsonResult(HttpReturnRnums.VCODE_IS_EMPTY);
//        }
        T_User_seller_infoModel queryModel = new T_User_seller_infoModel();
        queryModel.setEmail(req.getEmail());
        queryModel.setPassword(Digest.signMD5(req.getPassWd(), Digest.ENCODE));
        T_User_seller_infoModel queryResultModel = findByNamedParam(queryModel);
        if (queryResultModel == null) {
            return new JsonResult(HttpReturnRnums.LOGON_NAME_PWD_NET_MATCH);
        }
        if (StringUtils.equals("0", queryResultModel.getStatus())) {
            return new JsonResult(HttpReturnRnums.USER_NOT_ACTIVATE);
        }

        //set cookie
        UserCookieResp userCookieResp = new UserCookieResp();
        userCookieResp.setUser_id(queryResultModel.getUser_id());
        userCookieResp.setLogin_time(DateUtil.getToday());
        String userStr = JsonUtil.obj2string(userCookieResp);
        userStr = AES.aesEncrypt(userStr);

        CookieUtils.setCookie(request, response, GlobalSettings.SELLER_COOKIENAME, userStr);
        T_ProjectModel queryProjectModel = new T_ProjectModel();
        queryProjectModel.setUser_id(queryResultModel.getUser_id());
//        T_ProjectModel projectResultModel = findByNamedParam(queryProjectModel);
//        if (projectResultModel != null) {
//            queryResultModel.setProjectId(projectResultModel.getId());
//            queryResultModel.setProjectStatus(queryResultModel.getStatus());
//        }
        return new JsonResult(HttpReturnRnums.Success, queryResultModel);
    }

    /**
     * 激活
     *
     * @param req
     * @return
     */
    public JsonResult activate(UserActivateReq req) {
        //base params check
        HttpReturnRnums paramsCheckEnum = req.paramsCheck();
        if (paramsCheckEnum != HttpReturnRnums.Success) {
            return new JsonResult(paramsCheckEnum);
        }
        String codeOrg = AES.aesDecrypt(req.getCode());
        if (!StringUtils.contains(codeOrg, "_MARVEL_")) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }
        String[] codeArr = StringUtils.split(codeOrg, "_MARVEL_");
        String userId = codeArr[0];
        String email = codeArr[1];
        T_User_seller_infoModel queryModel = new T_User_seller_infoModel();
        queryModel.setEmail(email);
        queryModel.setUser_id(userId);
        T_User_seller_infoModel queryResultModel = findByNamedParam(queryModel);
        if (queryResultModel == null) {
            return new JsonResult(HttpReturnRnums.USER_NOT_EXIST);
        }
        if (StringUtils.equals("1", queryResultModel.getStatus())) {
            return new JsonResult(HttpReturnRnums.Success);
        }

        T_User_seller_infoModel updateModel = new T_User_seller_infoModel();
        updateModel.setUser_id(userId);
        updateModel.setStatus("1");
        update(updateModel);
        //创建用户钱包
        try {
            t_user_walletService.createWallet(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(HttpReturnRnums.Success);
    }

    /**
     * 发送重置密码邮件
     *
     * @param req
     * @return
     */
    public JsonResult sendRestPasswd(UserSendRestPasswdReq req,
                                     HttpServletRequest request) {
        HttpReturnRnums paramsCheckEnum = req.paramsCheck();
        if (paramsCheckEnum != HttpReturnRnums.Success) {
            return new JsonResult(paramsCheckEnum);
        }
        T_User_seller_infoModel queryModel = new T_User_seller_infoModel();
        queryModel.setEmail(req.getEmail());
        T_User_seller_infoModel queryResultModel = findByNamedParam(queryModel);
        if (queryResultModel == null) {
            return new JsonResult(HttpReturnRnums.USER_NOT_EXIST);
        }
        if (StringUtils.equals("0", queryResultModel.getStatus())) {
            return new JsonResult(HttpReturnRnums.USER_NOT_ACTIVATE);
        }
        sendRestPasswdEmail(queryResultModel, request);
        return new JsonResult(HttpReturnRnums.Success);
    }

    /**
     * TODO send reset password
     *
     * @param userInfo
     */
    private void sendRestPasswdEmail(T_User_seller_infoModel userInfo,
                                     HttpServletRequest request) {
        String activateCode = AES.aesEncrypt(userInfo.getUser_id() + "_MARVEL_" + userInfo.getEmail());
        String url = DOMAIN + "nologon/marvel/restpasswd?code=" + activateCode;
        setEmail(userInfo.getEmail(), url, EmailTemplateEnum.MODIFY_PWD, request);
    }

    /**
     * 重置密码
     *
     * @param req
     * @return
     */
    public JsonResult restPasswd(UserRestPasswdReq req) {
        HttpReturnRnums paramsCheckEnum = req.paramsCheck();
        if (paramsCheckEnum != HttpReturnRnums.Success) {
            return new JsonResult(paramsCheckEnum);
        }
        String codeOrg = AES.aesDecrypt(req.getCode());
        if (!StringUtils.contains(codeOrg, "_MARVEL_")) {
            return new JsonResult(paramsCheckEnum.ParaError);
        }
        String[] codeArr = StringUtils.split(codeOrg, "_MARVEL_");
        String userId = codeArr[0];
        String email = codeArr[1];
        T_User_seller_infoModel queryModel = new T_User_seller_infoModel();
        queryModel.setEmail(email);
        queryModel.setUser_id(userId);
        T_User_seller_infoModel queryResultModel = findByNamedParam(queryModel);
        if (queryResultModel == null) {
            return new JsonResult(HttpReturnRnums.USER_NOT_EXIST);
        }
        if (StringUtils.equals("0", queryResultModel.getStatus())) {
            return new JsonResult(HttpReturnRnums.USER_NOT_ACTIVATE);
        }
        T_User_seller_infoModel updateModel = new T_User_seller_infoModel();
        updateModel.setId(queryResultModel.getId());
        updateModel.setPassword(Digest.signMD5(req.getPassWd(), Digest.ENCODE));
        update(updateModel);
        return new JsonResult(HttpReturnRnums.Success);
    }

    /**
     * 保存单条数据     *      * @return
     */

    public int insert(T_User_seller_infoModel req) {
        return t_User_seller_infoMapper.insert(req);
    }

    /**
     * 批量增加数据     *      * @return
     */

    public int insertBatch(List<T_User_seller_infoModel> req) {
        return t_User_seller_infoMapper.insertBatch(req);
    }

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */

    public T_User_seller_infoModel findByNamedParam(T_User_seller_infoModel req) {
        return t_User_seller_infoMapper.findByNamedParam(req);
    }

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    public T_ProjectModel findByNamedParam(T_ProjectModel req) {
        return t_ProjectMapper.findByNamedParam(req);
    }

    /**
     * 根据对象查询所有数据     *      * @returnT_User_seller_infoService.java
     */

    public List<T_User_seller_infoModel> getAllList(T_User_seller_infoModel req) {
        return t_User_seller_infoMapper.findByNamedParamList(req);
    }

    /**
     * 根据对象查询所有分页数据     *      * @return
     */

    public PageInfo<T_User_seller_infoModel> getList(T_User_seller_infoModel req) {
        PageHelper.startPage(req.getPage_index(), req.getPage_size());
        List<T_User_seller_infoModel> list = t_User_seller_infoMapper.findByNamedParamList(req);
        return new PageInfo<T_User_seller_infoModel>(list);
    }

    /**
     * 更新指定对象     *      * @return
     */

    public int update(T_User_seller_infoModel req) {
        return t_User_seller_infoMapper.update(req);
    }

    /**
     * 删除指定数据     *      * @return
     */

    public int delete(BigInteger id) {
        return t_User_seller_infoMapper.delete(id);
    }

    /**
     * 根据条件统计数据量     *      * @return
     */

    public long count(T_User_seller_infoModel req) {
        return t_User_seller_infoMapper.count(req);
    }

    /**
     * 设置头象
     */
    public JsonResult setHeadFigure(UserSetHeadFigureReq req) {
        JsonResult js = new JsonResult();
        T_User_seller_infoModel t_user_seller_infoModel
                = new T_User_seller_infoModel();
        t_user_seller_infoModel.setUser_id(req.getUser_id());
        t_user_seller_infoModel.setHead_figure(req.getImg_url());
        t_User_seller_infoMapper.update(t_user_seller_infoModel);
        String key = RedissCacheKey.Seller_UserInfo_Key + req.getUser_id();
        redisService.remove(key);
        return js;
    }

    private void setEmail(String email, String url,
                          EmailTemplateEnum emailTemplate, HttpServletRequest request) {
        List<MngSendEmailResp> list = new ArrayList<MngSendEmailResp>();
        MngSendEmailResp user = new MngSendEmailResp();
        user.setKey("zhanghao");
        user.setValue(email);
        list.add(user);
        MngSendEmailResp callbackUrl = new MngSendEmailResp();
        callbackUrl.setKey("yanzhengma");
        callbackUrl.setValue(url);
        list.add(callbackUrl);
        t_mng_email_sysService.sendSystemEmailSync(
                emailTemplate, email, JsonUtil.obj2string(list), request);
    }
}